import {Injectable} from '@angular/core';
import {LoadingController, Loading, Platform} from "ionic-angular";

@Injectable()
export class LoadingService {
    loading: Loading;
    public noneLoading = false;

    constructor(public loadCtr: LoadingController,
                public platform: Platform) {
    }

    // limit = 60 * 1000;
    limitTimeout;

    private processLoading;
    private currentPercent = 0;
    private stopPercent;
    private maxGrowTime = 10000;
    private growTimeArr = [];
    private endInterval;
    private loadContentDom;

    /**
     * 显示加载提示
     */
    showLoading(enableBackdropDismiss?: boolean) {
        if (!this.noneLoading) {
            const p: any = {
                spinner: 'circles',
                content: "加载中"
            };
            if (enableBackdropDismiss) {
                p.enableBackdropDismiss = true;
            }
            this.loading = this.loadCtr.create(p);
            this.loading.present();

            // const self = this;
            // self.limitTimeout = setTimeout(() => {
            //     self.dismissLoading();
            // }, self.limit);
        }
    }

    resetStopPercent() {
        this.stopPercent = Math.floor(80 + Math.random() * 16);
        this.genIntervalArr();
    }

    showProLoading() {
        const loadingOption = {
            spinner: 'circles',
            content: "加载中0%",
            cssClass: 'pro-loading'
        };
        this.processLoading = this.loadCtr.create(loadingOption);
        this.processLoading.present().then(() => {
            this.loadContentDom = document.querySelector('.pro-loading .loading-content');
            this.resetStopPercent();
            this.setCurrentTime();
        });
    }

    genIntervalArr () {
        this.growTimeArr = [];
        let total = this.maxGrowTime;
        let num = this.stopPercent;

        while (num > 1){
            let rnd = this.genQualifiedTime(total, num);
            total -= rnd;
            this.growTimeArr.push(rnd);
            num --;
        }
    }

    genQualifiedTime (total, num) {
        let avgTime = Math.floor(total / this.stopPercent);
        let time = Math.floor(num/this.stopPercent * avgTime * Math.random() * 5);
        return time;
        // if (t < avgTime - 100 || t > avgTime + 100) {
        //     this.genQualifiedTime(total);
        // } else {
        //     return t;
        // }
    }

    setCurrentTime() {
        let interval =this.growTimeArr[this.currentPercent];
        let timeout = setTimeout(() => {
            this.currentPercent += 1;
            // this.processLoading.setContent(`加载中${this.currentPercent}%`);
            this.loadContentDom.innerHTML = `加载中${this.currentPercent}%`;
            if (this.currentPercent < this.stopPercent) {
                this.setCurrentTime();
            }
            clearTimeout(timeout);
        }, interval);
    }

    dismissProLoading() {
        // this.endInterval = setInterval(() => {
        //     if (this.currentPercent < 100) {
        //         this.currentPercent += 1;
        //         this.processLoading.setContent(`加载中${this.currentPercent}%`);
        //     } else {
        //         this.processLoading.setContent('加载中100%');
        //         this.processLoading.dismiss();
        //         clearInterval(this.endInterval);
        //         this.endInterval = null;
        //         this.currentPercent = 0;
        //     }
        // }, 1);
        // this.processLoading.setContent('加载中100%');
        this.loadContentDom.innerHTML = `加载中100%`;
        let timeout = setTimeout(() => {
            this.loadContentDom.parentNode.style.display = 'none';
            clearTimeout(timeout);
        }, 50);
        this.processLoading.dismiss();
    }

    errorDismiss() {
        this.processLoading.dismiss();
    }

    /**
     * 关闭加载提示
     */
    dismissLoading() {
        if (this.loading) {
            this.loading.dismiss();
        }
        // if (this.limitTimeout) {
        //     clearTimeout(this.limitTimeout);
        // }
    }
}
